<template>
  <div class="user-profile-container">
    <el-card class="user-profile-card">
      <div slot="header" class="clearfix">
        <span>个人信息管理</span>
      </div>
      
      <el-form 
        ref="profileForm" 
        :model="profileForm" 
        :rules="profileRules" 
        label-width="120px"
        class="profile-form"
      >
        <el-form-item label="用户名">
          <el-input v-model="profileForm.username" disabled></el-input>
        </el-form-item>
        
        <el-form-item label="公司名称" prop="companyName">
          <el-input 
            v-model="profileForm.companyName" 
            placeholder="请输入公司名称（可选）"
            clearable
          ></el-input>
        </el-form-item>
        
        <el-form-item label="当前密码" prop="currentPassword">
          <el-input 
            v-model="profileForm.currentPassword" 
            type="password" 
            placeholder="请输入当前密码"
          ></el-input>
        </el-form-item>
        
        <el-form-item label="新密码" prop="newPassword">
          <el-input 
            v-model="profileForm.newPassword" 
            type="password" 
            placeholder="请输入新密码（至少6位）"
          ></el-input>
        </el-form-item>
        
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input 
            v-model="profileForm.confirmPassword" 
            type="password" 
            placeholder="请再次输入新密码"
          ></el-input>
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="primary" 
            @click="updateProfile" 
            :loading="submitLoading"
          >
            保存信息
          </el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'UserProfile',
  data() {
    // 确认密码验证规则
    const validateConfirmPassword = (rule, value, callback) => {
      if (this.profileForm.newPassword && !value) {
        callback(new Error('请确认新密码'));
      } else if (value && value !== this.profileForm.newPassword) {
        callback(new Error('两次输入的密码不一致'));
      } else {
        callback();
      }
    };
    
    return {
      submitLoading: false,
      profileForm: {
        username: '',
        companyName: '',
        currentPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      profileRules: {
        currentPassword: [
          { required: true, message: '请输入当前密码', trigger: 'blur' }
        ],
        newPassword: [
          { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
        ],
        confirmPassword: [
          { validator: validateConfirmPassword, trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    this.loadUserProfile();
  },
  methods: {
    // 加载用户信息
    loadUserProfile() {
      const user = JSON.parse(localStorage.getItem('admin_user') || '{}');
      this.profileForm.username = user.username || '';
      this.profileForm.companyName = user.companyName || '';
    },
    
    // 更新用户信息
    updateProfile() {
      this.$refs.profileForm.validate((valid) => {
        if (valid) {
          this.submitLoading = true;
          
          // 准备提交数据
          const updateData = {
            currentPassword: this.profileForm.currentPassword
          };
          
          // 只有当字段有值时才添加到更新数据中
          if (this.profileForm.companyName) {
            updateData.companyName = this.profileForm.companyName;
          }
          
          if (this.profileForm.newPassword) {
            updateData.newPassword = this.profileForm.newPassword;
          }
          
          // 调用后端接口更新用户信息
          axios.post('/admin/user/profile', updateData)
            .then(response => {
              this.submitLoading = false;
              console.log('用户信息更新响应:', response);
              
              if (response.code ===200 || response.data.code === 200) {
                this.$message.success('用户信息更新成功');
                
                // 更新本地存储的用户信息
                const user = JSON.parse(localStorage.getItem('admin_user') || '{}');
                if (this.profileForm.companyName) {
                  user.companyName = this.profileForm.companyName;
                }
                localStorage.setItem('admin_user', JSON.stringify(user));
                
                // 发送事件通知Layout.vue更新标题
                window.dispatchEvent(new CustomEvent('userProfileUpdated', { detail: user }));
                
                // 更新页面标题
                this.updatePageTitle(user);
                
                // 重置密码字段
                this.profileForm.currentPassword = '';
                this.profileForm.newPassword = '';
                this.profileForm.confirmPassword = '';
              } else {
                this.$message.error(response.message || '更新失败');
              }
            })
            .catch(error => {
              this.submitLoading = false;
              // 兼容处理错误信息
              let errorMessage = error.message;
              if (error.response && error.response.data && error.response.data.message) {
                errorMessage = error.response.data.message;
              }
              this.$message.error('更新失败：' + errorMessage);
            });
        }
      });
    },
    
    // 重置表单
    resetForm() {
      this.$refs.profileForm.resetFields();
      this.loadUserProfile();
    },
    
    // 更新页面标题
    updatePageTitle(user) {
      // 构建系统标题
      const systemTitle = (user.companyName ? user.companyName + '管理系统' : '数据标注大屏后台管理系统');
      
      // 更新页面标题
      document.title = systemTitle;
      
      // 触发自定义事件通知其他组件更新
      window.dispatchEvent(new CustomEvent('systemTitleUpdated', { 
        detail: { 
          systemTitle: systemTitle,
          companyName: user.companyName
        } 
      }));
    },
  }
};
</script>

<style lang="scss" scoped>
.user-profile-container {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 120px);
  
  .user-profile-card {
    max-width: 600px;
    margin: 0 auto;
    
    :deep(.el-card__header) {
      background-color: #f5f7fa;
      border-bottom: 1px solid #e4e7ed;
      padding: 15px 20px;
      
      span {
        font-size: 18px;
        font-weight: 600;
        color: #303133;
      }
    }
    
    .profile-form {
      padding: 20px 0;
      
      :deep(.el-form-item) {
        margin-bottom: 25px;
        
        .el-form-item__label {
          font-weight: 500;
          color: #606266;
        }
        
        .el-input__inner {
          height: 40px;
          line-height: 40px;
        }
      }
    }
  }
}
</style>